package org.jeecg.modules.system.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DictCode;
import org.jeecg.common.constant.enums.SysLogOperateType;
import org.jeecg.common.constant.enums.SysLogType;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysLog;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.mapper.SysDictMapper;
import org.jeecg.modules.system.service.ISysLogService;
import org.jeecg.modules.system.vo.SysLogColumnarStatisticsVO;
import org.jeecg.modules.system.vo.SysLogConfigReq;
import org.jeecg.modules.system.vo.SysLogOperateTypeReq;
import org.jeecg.modules.system.vo.SysLogOperateTypeVO;
import org.jeecg.modules.system.vo.SysLogPageReq;
import org.jeecg.modules.system.vo.SysLogStatisticsReq;
import org.jeecg.modules.system.vo.SysLogStatisticsVO;
import org.jeecg.modules.system.vo.SysLogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 系统日志表 前端控制器
 * </p>
 *
 * @Author zhangweijian
 * @since 2018-12-26
 */
@Api(tags = "日志管理")
@RestController
@RequestMapping("/sys/log")
@Slf4j
public class SysLogController {

	@Autowired
	private ISysBaseAPI sysBaseAPI;

	@Autowired
	private ISysLogService sysLogService;

	@Autowired
	private SysDictMapper sysDictMapper;

	/**
	 * @功能：查询日志记录
	 * @param syslog
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value = "查询日志管理的操作日志列表", notes = "查询日志管理的操作日志列表")
	// @AutoLog(value = "查询日志管理的操作日志列表", operateType =
	// CommonConstant.OPERATE_TYPE_AUDIT_QUERY)
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result<IPage<SysLogVO>> queryPageList(@Valid SysLogPageReq sysLogPageReq, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		log.info("sysLogPageReq:" + sysLogPageReq.getOrderType() + "," + sysLogPageReq.getStartTime() + "," + sysLogPageReq.getEndTime());
		Result<IPage<SysLogVO>> result = new Result<IPage<SysLogVO>>();
		// QueryWrapper<SysLog> queryWrapper =
		// QueryGenerator.initQueryWrapper(syslog, req.getParameterMap());
		Page<SysLog> page = new Page<SysLog>(pageNo, pageSize);

		handleRemoveSpecialOperateType(sysLogPageReq);
		
		
		IPage<SysLogVO> pageList = sysLogService.queryPage(page, sysLogPageReq);
		log.info("查询当前页：" + pageList.getCurrent());
		log.info("查询当前页数量：" + pageList.getSize());
		log.info("查询结果数量：" + pageList.getRecords().size());
		log.info("数据总数：" + pageList.getTotal());
		result.setSuccess(true);
		result.setResult(pageList);

		if (StringUtils.isBlank(sysLogPageReq.getTitle())) {
			// sysBaseAPI.addLog("查询易分析的操作日志列表",
			// CommonConstant.LOG_TYPE_OPERATE,
			// CommonConstant.OPERATE_TYPE_AUDIT_QUERY);
			sysBaseAPI.addLog("查询易分析的操作日志列表" + sysLogPageReq.toString(), SysLogType.OPERATE, SysLogOperateType.AUDIT_QUERY, null, null, "系统管理-易分析日志");
		} else {
			if (sysLogPageReq.getTitle().equals("系统日志") || sysLogPageReq.getTitle().equals("业务日志")) {
				sysBaseAPI.addLog("查询日志管理的" + sysLogPageReq.getTitle() + "列表" + sysLogPageReq.toString(), SysLogType.OPERATE, SysLogOperateType.AUDIT_QUERY, null, null, "系统管理-日志管理-" + sysLogPageReq.getTitle());

			} else {
				sysBaseAPI.addLog("查询易分析的" + sysLogPageReq.getTitle() + "列表" + sysLogPageReq.toString(), SysLogType.OPERATE, SysLogOperateType.AUDIT_QUERY, null, null, "系统管理-易分析日志-" + sysLogPageReq.getTitle());
			}
		}

		return result;
	}

	private void handleRemoveSpecialOperateType(SysLogPageReq sysLogPageReq) {
		// sgccsj sgccyfx 开头的不要备份、恢复、日志统计
		List<String> userIds = new ArrayList<>();
		userIds.add("sgccsj");
		userIds.add("sgccyfx");
		
		List<String> userIdAqsj = new ArrayList<>();
		userIdAqsj.add("sgccaqsj");
		
		// 获取登录用户信息
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (sysUser !=null) {
			for (String userId :userIds) {
				if (sysUser.getUsername().startsWith(userId)) {
					if (sysLogPageReq.getExcludeOperateType() == null) {
						sysLogPageReq.setExcludeOperateType(new ArrayList<Integer>());
					}
					
					sysLogPageReq.getExcludeOperateType().add(CommonConstant.OPERATE_TYPE_BACKUP); // 备份
					sysLogPageReq.getExcludeOperateType().add(CommonConstant.OPERATE_TYPE_RESUME); // 恢复
					sysLogPageReq.getExcludeOperateType().add(CommonConstant.OPERATE_TYPE_LOG_STATISTICS); // 日志统计
					
					sysLogPageReq.setIsAq(0);
					break;
				}
			}
			
			for (String userId :userIdAqsj) {
				if (sysUser.getUsername().startsWith(userId)) {
					if (sysLogPageReq.getExcludeOperateType() == null) {
						sysLogPageReq.setExcludeOperateType(new ArrayList<Integer>());
					}
					
					sysLogPageReq.getExcludeOperateType().add(CommonConstant.OPERATE_TYPE_LOG_DELETE); // 日志删除
				}
			}
		}
	}

	@ApiOperation(value = "日志统计列表", notes = "日志统计列表")
	@AutoLog(value = "查询日志统计列表", operateType = CommonConstant.OPERATE_TYPE_LOG_STATISTICS, module = "系统管理-日志统计")
	@RequestMapping(value = "/logStatistics", method = RequestMethod.GET)
	public Result<IPage<SysLogStatisticsVO>> logStatistics(@Valid SysLogStatisticsReq sysLogStatisticsRwq, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		Result<IPage<SysLogStatisticsVO>> result = new Result<IPage<SysLogStatisticsVO>>();
		Page<SysLogStatisticsVO> page = new Page<SysLogStatisticsVO>(pageNo, pageSize);

		IPage<SysLogStatisticsVO> pageList = sysLogService.logStatistics(page, sysLogStatisticsRwq);

		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	@ApiOperation(value = "日志柱状统计", notes = "日志柱状统计")
	@AutoLog(value = "查看日志柱状统计", operateType = CommonConstant.OPERATE_TYPE_LOG_STATISTICS, module = "系统管理-日志统计")
	@RequestMapping(value = "/columnarStatistics", method = RequestMethod.GET)
	public Result<List<SysLogColumnarStatisticsVO>> columnarStatistics(@Valid SysLogStatisticsReq sysLogStatisticsRwq) {
		Result<List<SysLogColumnarStatisticsVO>> result = new Result<List<SysLogColumnarStatisticsVO>>();
		List<SysLogColumnarStatisticsVO> list = sysLogService.columnarStatistics(sysLogStatisticsRwq);

		result.setSuccess(true);
		result.setResult(list);
		return result;
	}

	@ApiOperation(value = "日志配置", notes = "日志配置")
	// @AutoLog(value = "修改日志配置", operateType = CommonConstant.OPERATE_TYPE_LOG_CONFIG, module = "系统管理-日志配置")
	@RequestMapping(value = "/config", method = RequestMethod.GET)
	public Result<String> config(@Valid SysLogConfigReq req) {
		Result<String> result = new Result<String>();
		Map<String, Integer> items = sysLogService.config(req);
		boolean  notChange = true;
		if(req.getAddSwitch() != null) {
			if(!req.getAddSwitch().equals(items.get("addSwitch"))) {
				String s = req.getAddSwitch() == 1?"启用":"关闭";
				s = s + "新增日志开关";
				notChange = false;
				sysBaseAPI.addLog("修改日志配置:" + s, SysLogType.OPERATE, SysLogOperateType.LOG_CONFIG, null, null, "系统管理-日志配置");
			}
			if(!req.getAppQuerySwitch().equals(items.get("appQuerySwitch"))) {
				String s = req.getAppQuerySwitch() == 1?"启用":"关闭";
				s = s + "应用资源列表查询日志开关";
				notChange = false;
				sysBaseAPI.addLog("修改日志配置:" + s, SysLogType.OPERATE, SysLogOperateType.LOG_CONFIG, null, "appQuerySwitch", "系统管理-日志配置");
			}
			if(!req.getCapacity().equals(items.get("capacity"))) {
				String s = "日志告警容量修改为"+req.getCapacity();
				notChange = false;
				sysBaseAPI.addLog("修改日志配置:" + s, SysLogType.OPERATE, SysLogOperateType.LOG_CONFIG, null, "capacity", "系统管理-日志配置");
			}
			if(!req.getDeleteSwitch().equals(items.get("deleteSwitch"))) {
				String s = req.getDeleteSwitch() == 1?"启用":"关闭";
				s = s + "删除日志开关";
				notChange = false;
				sysBaseAPI.addLog("修改日志配置:" + s, SysLogType.OPERATE, SysLogOperateType.LOG_CONFIG, null, null, "系统管理-日志配置");
			}
			if(!req.getDetailSwitch().equals(items.get("detailSwitch"))) {
				String s = req.getDetailSwitch() == 1?"启用":"关闭";
				s = s + "查看日志开关";
				notChange = false;
				sysBaseAPI.addLog("修改日志配置:" + s, SysLogType.OPERATE, SysLogOperateType.LOG_CONFIG, null, null, "系统管理-日志配置");
			}
			if(!req.getSqlSwitch().equals(items.get("sqlSwitch"))) {
				String s = req.getSqlSwitch() == 1?"启用":"关闭";
				s = s + "SQL日志开关";
				notChange = false;
				sysBaseAPI.addLog("修改日志配置:" + s, SysLogType.OPERATE, SysLogOperateType.LOG_CONFIG, null, null, "系统管理-日志配置");
			}
			if(!req.getUpdateSwitch().equals(items.get("updateSwitch"))) {
				String s = req.getUpdateSwitch() == 1?"启用":"关闭";
				s = s + "修改日志开关";
				notChange = false;
				sysBaseAPI.addLog("修改日志配置:" + s, SysLogType.OPERATE, SysLogOperateType.LOG_CONFIG, null, null, "系统管理-日志配置");
			}
			if(!req.getListSwitch().equals(items.get("listSwitch"))) {
				String s = req.getListSwitch() == 1?"启用":"关闭";
				s = s + "业务查询日志开关";
				notChange = false;
				sysBaseAPI.addLog("修改日志配置:" + s, SysLogType.OPERATE, SysLogOperateType.LOG_CONFIG, null, null, "系统管理-日志配置");
			}
			if(notChange) {
				sysBaseAPI.addLog("修改日志配置:" + "未更改日志配置", SysLogType.OPERATE, SysLogOperateType.LOG_CONFIG, null, null, "系统管理-日志配置");
			}
		}
		result.setSuccess(true);
		return result;
	}

	@ApiOperation(value = "查看日志配置", notes = "获取日志配置")
	@AutoLog(value = "查看日志配置", operateType = CommonConstant.OPERATE_TYPE_AUDIT_QUERY, module = "系统管理-日志配置")
	@RequestMapping(value = "/getConfig", method = RequestMethod.GET)
	public Result<List<DictModel>> getConfig() {
		Result<List<DictModel>> result = new Result<List<DictModel>>();

		List<DictModel> values = sysDictMapper.queryDictItemsByCode(DictCode.LOG_CONFIG.getCode());

		result.setSuccess(true);
		result.setResult(values);
		return result;
	}

	/**
	 * @功能：删除单个日志记录
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	public Result<SysLog> delete(@RequestParam(name = "id", required = true) String id) {
		Result<SysLog> result = new Result<SysLog>();
		SysLog sysLog = sysLogService.getById(id);
		if (sysLog == null) {
			result.error500("未找到对应实体");
		} else {
			boolean ok = sysLogService.removeById(id);
			if (ok) {
				result.success("删除成功!");
			}
		}
		return result;
	}

	/**
	 * @功能：批量，全部清空日志记录
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteLogBatch", method = RequestMethod.DELETE)
	public Result<SysRole> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		Result<SysRole> result = new Result<SysRole>();
		if (ids == null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		} else {
			if ("allclear".equals(ids)) {
				this.sysLogService.removeAll();
				result.success("清除成功!");
			}
			this.sysLogService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	 * @功能：查询日志记录
	 * @param syslog
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value = "查看日志操作类型列表", notes = "查询日志操作类型列表")
	@RequestMapping(value = "/operate_type_list", method = RequestMethod.GET)
	public Result<List<SysLogOperateTypeVO>> operateTypeList(@Valid SysLogOperateTypeReq req) {
		Result<List<SysLogOperateTypeVO>> result = new Result<>();
		List<SysLogOperateTypeVO> res = new ArrayList<>();
		List<SysLogOperateType> sts = SysLogOperateType.getAll();

		// 只查询日志类型
		if (req.getLogType() != null && req.getIsSystem() == null) {
			SysLogType lt = SysLogType.getByType(req.getLogType());
			if (lt != null) {
				sts = SysLogOperateType.getByLogType(lt);
			}
		}

		// 只查询业务类型
		if (req.getIsSystem() != null && req.getLogType() == null) {
			sts = SysLogOperateType.getByIsSystem(req.getIsSystem());
		}

		// 并列查询
		if (req.getIsSystem() != null && req.getLogType() != null) {
			SysLogType lt = SysLogType.getByType(req.getLogType());
			if (lt != null) {
				sts = SysLogOperateType.getByLogTypeAndIsSystem(lt, req.getIsSystem());
			}
		}

		if (req.getIncludeOperateType() != null) {
			List<SysLogOperateType> stssub = SysLogOperateType.getByLogTypes(req.getIncludeOperateType());
			sts.addAll(stssub);
		}

		
		// sgccsj sgccyfx 开头的不要备份、恢复、日志统计
		List<String> userIds = new ArrayList<>();
		userIds.add("sgccsj");
		userIds.add("sgccyfx");
		
		// sgccaqsj 开头的不要日志删除
		List<String> userIdAqsj = new ArrayList<>();
		userIdAqsj.add("sgccaqsj");
		
		// 获取登录用户信息
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (sysUser !=null) {
			for (String userId :userIds) {
				if (sysUser.getUsername().startsWith(userId)) {
					if (req.getExcludeOperateType() == null) {
						req.setExcludeOperateType(new ArrayList<Integer>());
					}
					
					req.getExcludeOperateType().add(CommonConstant.OPERATE_TYPE_BACKUP); // 备份
					req.getExcludeOperateType().add(CommonConstant.OPERATE_TYPE_RESUME); // 恢复
					req.getExcludeOperateType().add(CommonConstant.OPERATE_TYPE_LOG_STATISTICS); // 日志统计
					
					break;
				}
			}
			
			for (String userId :userIdAqsj) {
				if (sysUser.getUsername().startsWith(userId)) {
					if (req.getExcludeOperateType() == null) {
						req.setExcludeOperateType(new ArrayList<Integer>());
					}
					
					req.getExcludeOperateType().add(CommonConstant.OPERATE_TYPE_LOG_DELETE); // 日志删除
				}
			}
		}
		
		
		for (SysLogOperateType st : sts) {
			if (req.getExcludeOperateType() != null && req.getExcludeOperateType().contains(st.getType())) {
				continue;
			}
			SysLogOperateTypeVO vo = new SysLogOperateTypeVO();
			vo.setName(st.getName());
			vo.setValue(st.getType());
			vo.setEventType(st.getIsSystem() ? 1 : 0);
			res.add(vo);
		}
		result.setResult(res);
		return result;
	}

	@ApiOperation(value = "日志备份", notes = "日志备份")
	@AutoLog(value = "日志备份", operateType = CommonConstant.OPERATE_TYPE_BACKUP, module = "系统管理-日志管理")
	@RequestMapping(value = "/backup", method = RequestMethod.GET)
	public Result<String> backup(@Valid SysLogPageReq sysLogPageReq) {
		Result<String> result = new Result<>();
		sysLogService.backup(sysLogPageReq);

		result.setResult("备份成功");
		return result;
	}
	
	@ApiOperation(value = "删除日志", notes = "删除日志")
	@AutoLog(value = "删除业务日志", operateType = CommonConstant.OPERATE_TYPE_LOG_DELETE, module = "系统管理-日志管理-业务日志")
	@RequestMapping(value = "/deleteLogs", method = RequestMethod.GET)
	public Result<String> deleteLogs(@Valid SysLogPageReq sysLogPageReq) {
		Result<String> result = new Result<>();
		sysLogPageReq.setLogContent(null);
		sysLogPageReq.setUsername(null);
		sysLogPageReq.setIp(null);
		sysLogPageReq.setStartTime(null);
		sysLogPageReq.setOperateType(null);
		sysLogPageReq.setEventType(null);
		sysLogPageReq.setOrderType(null);
		sysLogService.deleteLogs(sysLogPageReq);
		result.setResult("删除业务日志成功");
		
		return result;
	}

	@ApiOperation(value = "日志恢复", notes = "日志恢复")
	@AutoLog(value = "日志恢复", operateType = CommonConstant.OPERATE_TYPE_RESUME, module = "系统管理-日志管理")
	@RequestMapping(value = "/resume", method = RequestMethod.GET)
	public Result<String> resume(@Valid SysLogPageReq sysLogPageReq) {
		Result<String> result = new Result<>();

		sysLogService.resume(sysLogPageReq);

		result.setResult("恢复成功");
		return result;
	}
}
